package cn.wjdiankong.levideo.activity;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import com.ss.android.common.applog.GlobalContext;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.util.TypedValue;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import cn.wjdiankong.levideo.R;
import cn.wjdiankong.levideo.dialog.DragTabSortDialog;
import cn.wjdiankong.levideo.fragment.BaseFragment;
import cn.wjdiankong.levideo.fragment.DouyinFragment;
import cn.wjdiankong.levideo.fragment.HuoshanFragment;
import cn.wjdiankong.levideo.fragment.KuaishouFragment;
import cn.wjdiankong.levideo.fragment.MiaopaiFragment;
import cn.wjdiankong.levideo.list.adapter.LevideoFragmentAdapter;
import cn.wjdiankong.levideo.utils.Const;
import cn.wjdiankong.levideo.utils.Logger;
import cn.wjdiankong.levideo.utils.UIUtil;
import cn.wjdiankong.levideo.utils.UmengReportUtils;
import cn.wjdiankong.levideo.view.PagerSlidingTabStrip;
import cn.wjdiankong.levideo.view.PagerSlidingTabStrip.ViewPageChangeListener;
import cn.wjdiankong.levideo.view.slidemenu.LevideoSliddingMenu;
import cn.wjdiankong.toutiaovideo.UsageGuideActivity;
import net.youmi.android.nm.sp.SpotManager;
import net.youmi.android.nm.vdo.VideoAdManager;

@SuppressLint("NewApi")
public class MainActivity extends BaseActivity implements OnClickListener{

	private PagerSlidingTabStrip tabs;
	private ViewPager pager;
	private LevideoFragmentAdapter adapter;

	private LevideoSliddingMenu slideMenu;

	private ArrayList<String> titles = new ArrayList<String>();
	private List<BaseFragment> fragmentList = new ArrayList<BaseFragment>();
	private int curPosition = 0;

	public final static int CODE_SETTING_SORT_TAB = 1024;
	public final static int CODE_SETTING_SORT_TAB_REULT = 1025;

	private List<Integer> tabSortList = new ArrayList<Integer>(4);

	private DouyinFragment douyinFragment;
	private KuaishouFragment kuaishouFragment;
	private MiaopaiFragment miaopaiFragment;
	private HuoshanFragment huoshanFragment;

	private View leftMenuView;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		init();
		isGestureFinish = false;
	}

	private void init(){
		initView();
		initData();
	}

	protected void initView(){
		super.initView();
		tabs = (PagerSlidingTabStrip) findViewById(R.id.tabs);
		pager = (ViewPager) findViewById(R.id.pager);
		setTitle("酱爆视频");
		setLeftImg(R.drawable.title_menu_icon);
		setRightImg(R.drawable.title_menu_user_icon);
		initSlideMenu();
	}

	protected void initData(){
		super.initData();
		douyinFragment = DouyinFragment.newInstance(0, "抖音", Const.VIDEO_TYPE_DOUYIN);
		kuaishouFragment = KuaishouFragment.newInstance(1, "快手", Const.VIDEO_TYPE_KUAISHOU);
		huoshanFragment = HuoshanFragment.newInstance(2, "火山", Const.VIDEO_TYPE_HUOSHAN);
		miaopaiFragment = MiaopaiFragment.newInstance(3, "秒拍", Const.VIDEO_TYPE_MIAOPAI);
		initTab();
	}

	private void initSlideMenu(){
		leftMenuView = findViewById(R.id.left_menu_layout);
		leftMenuView.setVisibility(View.GONE);
		slideMenu = (LevideoSliddingMenu) findViewById(R.id.qqsm);
		leftMenuView.setOnClickListener(this);
		findViewById(R.id.layout_login).setOnClickListener(this);
		findViewById(R.id.toutiao_download).setOnClickListener(this);
		findViewById(R.id.setting_layout).setOnClickListener(this);
		findViewById(R.id.about_me).setOnClickListener(this);
		findViewById(R.id.download_video).setOnClickListener(this);
		findViewById(R.id.book_layout).setOnClickListener(this);
		findViewById(R.id.supportapp_layout).setOnClickListener(this);
	}

	private void initTab(){
		tabSortList = DragTabSortDialog.getTagSortData();
		if(tabSortList == null || tabSortList.size() == 0){
			tabSortList = new ArrayList<Integer>(4);
			tabSortList.add(Const.VIDEO_TYPE_DOUYIN);
			tabSortList.add(Const.VIDEO_TYPE_KUAISHOU);
			tabSortList.add(Const.VIDEO_TYPE_HUOSHAN);
			tabSortList.add(Const.VIDEO_TYPE_MIAOPAI);
		}
		titles.clear();
		fragmentList.clear();
		for(Integer i : tabSortList){
			switch(i){
			case Const.VIDEO_TYPE_DOUYIN:
				titles.add("抖音");
				fragmentList.add(douyinFragment);
				break;
			case Const.VIDEO_TYPE_KUAISHOU:
				titles.add("快手");
				fragmentList.add(kuaishouFragment);
				break;
			case Const.VIDEO_TYPE_HUOSHAN:
				titles.add("火山");
				fragmentList.add(huoshanFragment);
				break;
			case Const.VIDEO_TYPE_MIAOPAI:
				titles.add("秒拍");
				fragmentList.add(miaopaiFragment);
				break;
			}
		}
		adapter = new LevideoFragmentAdapter(getSupportFragmentManager());
		adapter.setFragmentList(fragmentList);
		adapter.setTitleList(titles);
		pager.setOffscreenPageLimit(4);
		int pageMargin = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 4, getResources().getDisplayMetrics());
		pager.setPageMargin(pageMargin);
		pager.setAdapter(adapter);
		pager.setCurrentItem(curPosition, true);
		tabs.setIndicatorColor(Const.theme_bg);
		tabs.setIndicatorHeight(UIUtil.dip2px(GlobalContext.getContext(), 2));
		tabs.setTextSize(UIUtil.dip2px(GlobalContext.getContext(), 14));
		tabs.setUnderlineHeight(0);
		tabs.setViewPager(pager);
		tabs.setViewPageChangeListener(new ViewPageChangeListener(){
			@Override
			public void changeViewPage(int position) {
				curPosition = position;
			}
		});
	}

	public static void startDefault(Context context){
		Intent intent = new Intent(context, MainActivity.class);
		context.startActivity(intent);
	}

	/** 
	 * 菜单、返回键响应 
	 */  
	@Override  
	public boolean onKeyDown(int keyCode, KeyEvent event) {  
		if(keyCode == KeyEvent.KEYCODE_BACK)  { 
			if(slideMenu.isOpen()){
				slideMenu.closeMenu();
			}else{
				exitBy2Click();//调用双击退出函数  
			}
		}  
		return false;  
	}  

	private static boolean isExit = false;  

	private void exitBy2Click() {
		Timer tExit = null;
		if (isExit == false) {
			isExit = true; // 准备退出  
			UIUtil.showShortHintToast(getApplicationContext(), "再按一次退出程序");  
			tExit = new Timer();  
			tExit.schedule(new TimerTask() {  
				@Override  
				public void run() {  
					isExit = false; // 取消退出  
				}
			}, 2000); // 如果2秒钟内没有按下返回键，则启动定时器取消掉刚才执行的任务  
		} else {
			// 退出应用时调用，用于释放资源
			// 如果无法保证应用主界面的 onDestroy() 方法被执行到，请移动以下接口到应用的退出逻辑里面调用
			// 插屏广告（包括普通插屏广告、轮播插屏广告、原生插屏广告）
			SpotManager.getInstance(getApplicationContext()).onAppExit();
			// 视频广告（包括普通视频广告、原生视频广告）
			VideoAdManager.getInstance(getApplicationContext()).onAppExit();
			finish();
			System.exit(0);
		}
	}

	@Override
	protected void clickLeftImg(){
		leftMenuView.setVisibility(View.VISIBLE);
		slideMenu.toggleMenu();
		UmengReportUtils.report(UmengReportUtils.MAIN_LEFT_MENU);
	}

	@Override
	protected void clickRightImg(){
		showLoginDialog();
		UmengReportUtils.report(UmengReportUtils.MAIN_USER_LOGIN);
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		Logger.log("code:"+resultCode);
		if(resultCode == CODE_SETTING_SORT_TAB_REULT){
			resetTab();
		}
	}

	private void resetTab(){
		//检查tab的顺序是否发生变化
		List<Integer> sortValue = DragTabSortDialog.getTagSortData();
		if(sortValue != null && sortValue.size() == 4){
			boolean isTabSortChange = false;
			for(int i=0;i<4;i++){
				if(tabSortList.get(i) != sortValue.get(i)){
					isTabSortChange = true;
					break;
				}
			}
			if(isTabSortChange){
				List<BaseFragment> tempFragmentList = new ArrayList<BaseFragment>();
				List<String> tempTitleList = new ArrayList<String>();
				for(Integer val : sortValue){
					switch(val){
					case Const.VIDEO_TYPE_DOUYIN:
						tempFragmentList.add(douyinFragment);
						tempTitleList.add("抖音");
						break;
					case Const.VIDEO_TYPE_HUOSHAN:
						tempFragmentList.add(huoshanFragment);
						tempTitleList.add("火山");
						break;
					case Const.VIDEO_TYPE_KUAISHOU:
						tempFragmentList.add(kuaishouFragment);
						tempTitleList.add("快手");
						break;
					case Const.VIDEO_TYPE_MIAOPAI:
						tempFragmentList.add(miaopaiFragment);
						tempTitleList.add("秒拍");
						break;
					}
				}
				titles.clear();
				titles.addAll(tempTitleList);
				fragmentList.clear();
				fragmentList.addAll(tempFragmentList);
				adapter.setFragmentList(fragmentList);
				adapter.notifyDataSetChanged();
				tabs.updateTabTitle(titles);//更新tab的标题
				pager.setCurrentItem(0, true);
				StringBuilder tabStr = new StringBuilder();
				for(String str : titles){
					tabStr.append(str+",");
				}
				HashMap<String, String> params = new HashMap<String, String>();
				params.put("new_sort", tabStr.toString());
				UmengReportUtils.report(UmengReportUtils.SETTING_TABSORT_RESULT, params);
			}
		}
	}

	private void delayCloseMenu(){
		slideMenu.postDelayed(new Runnable() {
			@Override
			public void run() {
				slideMenu.closeMenu();
			}
		}, 1000);
	}

	@Override
	public void onClick(View v) {
		Logger.log("click view id:"+v.getId());
		switch(v.getId()){
		case R.id.layout_login://左侧栏登录
			showLoginDialog();
			slideMenu.closeMenu();
			UmengReportUtils.report(UmengReportUtils.MAIN_MENU_USER_LOGIN);
			break;
		case R.id.about_me://左侧栏关于我
			AboutMeActivity.startDefault(this);
			delayCloseMenu();
			UmengReportUtils.report(UmengReportUtils.MAIN_MENU_ABOUT_ME);
			break;
		case R.id.toutiao_download://左侧栏头条视频下载器
			UsageGuideActivity.startDefault(this);
			delayCloseMenu();
			UmengReportUtils.report(UmengReportUtils.MAIN_MENU_TOUTIAO_GUIDE);
			break;
		case R.id.download_video://左侧栏本地视频
			LocalVideoActivity.startDefault(this);
			delayCloseMenu();
			UmengReportUtils.report(UmengReportUtils.MAIN_MENU_LOCALVIDEO);
			break;
		case R.id.setting_layout://左侧栏的设置
			SettingActivity.startDefaultResult(this, CODE_SETTING_SORT_TAB);
			delayCloseMenu();
			UmengReportUtils.report(UmengReportUtils.MAIN_MENU_SETTING);
			break;
		case R.id.book_layout://图书
			BookActivity.startDefault(this);
			delayCloseMenu();
			UmengReportUtils.report(UmengReportUtils.MAIN_MENU_BOOK);
			break;
		case R.id.supportapp_layout:
			SupportAppActivity.startDefault(this);
			delayCloseMenu();
			UmengReportUtils.report(UmengReportUtils.MAIN_MENU_SUPPORT_APP);
			break;
		case R.id.left_menu_layout://侧边栏
			slideMenu.toggleMenu();
			UmengReportUtils.report(UmengReportUtils.MAIN_MENU_CLOSE);
			break;
		}
	}

	@Override
	protected String getPageName() {
		return "main";
	}

}